/* eslint-disable no-unused-vars */

/**
 * 向后端请求用户的菜单，动态生成路由
 *@import constantRouterMap  默认路由
 *
 */
 import Vue from 'vue'
 import router from '@/router'
 import { constantRouterMap, asyncRouterMap } from '@/config/router.config'

 const asyncRouter = {
   state: {
     routers: constantRouterMap,
     addRouters: [],
     isMicro: window.__POWERED_BY_QIANKUN__,
     microRulePath: ''
   },
   mutations: {
     SET_ROUTERS: (state, routers) => {
       state.addRouters = routers
       state.routers = constantRouterMap.concat(routers)
     },
     SET_MicroRulePath: (state, path) => {
       console.log('SET_MicroRulePath', path)
       state.microRulePath = path
     }
   },
   actions: {
     GenerateRoutes ({ commit, rootGetters }) {
       return new Promise((resolve, reject) => {
           console.log(asyncRouterMap)
           commit('SET_ROUTERS', asyncRouterMap)
           resolve()
       })
     },
     // 设置子应用路由规则
     SET_MicroRulePath ({ commit, state }, props) {
       return new Promise((resolve, reject) => {
         const routerBase = props.routerBase
         const portalPubilcPath = props.portalPublicPath
         if (portalPubilcPath !== '' && portalPubilcPath !== '/') {
           commit('SET_MicroRulePath', routerBase.replace(new RegExp('^' + portalPubilcPath), ''))
         } else {
           commit('SET_MicroRulePath', routerBase)
         }
         resolve()
       })
      },
     // 子应用路由跳转
     MicroNavigateTo ({ state }, route) {
      return new Promise((resolve, reject) => {
        if (typeof route === 'string') {
          const routePath = `${state.microRulePath}${route}`
          if (state.isMicro && Vue.prototype.$microTabsApi) {
            Vue.prototype.$microTabsApi.open(routePath)
          } else {
            router.push(routePath)
          }
          resolve()
        } else if (typeof route === 'object') {
          if (route.hasOwnProperty('path')) {
            const { path } = route
            const routePath = `${state.microRulePath}${path}`
            if (state.isMicro && Vue.prototype.$microTabsApi) {
              Vue.prototype.$microTabsApi.open(Object.assign({}, route, { path: routePath }))
            } else {
              router.push(Object.assign({}, route, { path: routePath }))
            }
            resolve()
          } else {
            reject(new Error('路由跳转参数错误'))
          }
        }
      })
     }
   }
 }

 export default asyncRouter
